import classnames from 'classnames'
import { useNavigate } from 'react-router'
import { NavBar, SearchBar } from 'antd-mobile'

import Icon from '@/components/icon'
import styles from './index.module.scss'
import { useEffect, useState } from 'react'
import { getSuggestApi } from '@/api/search'
// 1. 导入 lodash 中的防抖函数
import debounce from 'lodash/debounce'
// 2. 导入ahooks 防抖函数
import { useDebounceFn } from 'ahooks'

// 对搜索联想词获取做防抖处理
// 语法：debounce(callback防抖逻辑, time延迟时间)
// const run = debounce(async (key: string) => {
//   if (!key.trim()) return
//   console.log('搜索关键词：', key)
//   const { data } = await getSuggestApi({ q: key })
//   console.log('根据输入的关键词匹配联想词列表：', data)
// }, 600)

const SearchPage = () => {
  const history = useNavigate()

  // 1. 搜索关键词（keyWrod）变量
  const [keyWord, setKeyWord] = useState('')
  // 2. 搜索联想词变量
  const [suggest, setSuggest] = useState<string[]>([])
  // 3. 搜索历史记录
  const [historyList, setHistoryList] = useState<string[]>(
    JSON.parse(localStorage.getItem('search-keys') || '[]')
  )
  // 使用ahooks处理防抖
  const { run } = useDebounceFn(
    async (key: string) => {
      if (!key.trim()) return setSuggest([])
      // console.log('搜索关键词：', key)
      const { data } = await getSuggestApi({ q: key })
      // console.log('根据输入的关键词匹配联想词列表：', data)
      // 处理联想词高亮=》把联想词中第一个key使用<span>key</span>
      const _suggest = data.options.map((item) => {
        // item.replace(要替换的字符串, 替换结果)
        return item && item.replace(key, `<span>${key}</span>`)
      })
      setSuggest(_suggest)
    },
    {
      wait: 600,
    }
  )
  // 输入搜索关键词
  const onSearch = async (key: string) => {
    setKeyWord(key)
    // 注意❓：判断非空放到视图刷新之后
    // if (!key.trim()) return
    // console.log('搜索关键词：', key)
    // const { data } = await getSuggestApi({ q: key })
    // console.log('根据输入的关键词匹配联想词列表：', data)
    run(key)
  }

  // 跳转搜索结果页面
  /**
   *
   * @param key 跳转搜索的关键词
   */
  const saveHistory = (key: string) => {
    /**
     * 1. 排除重复的搜索关键词
     * 2. 没有重复的才进行存储
     */
    // 说明：如果之前历史记录中有当前新增的key，some方法返回true
    if (historyList.some((item) => item === key)) return
    setHistoryList([key, ...historyList])
  }
  useEffect(() => {
    // console.log('监听historyList变化，持久化存储:', historyList)
    // 监听historyList变化，持久化存储
    localStorage.setItem('search-keys', JSON.stringify(historyList))
  }, [historyList])
  /**
   *
   * @param key 搜索内容关键词
   */
  const goSearch = (key: string) => {
    setTimeout(() => {
      // 说明❓：添加定时器，解决页面跳转后，useEffect监听不执行问题
      history(`/search/result?q=${key}`)
    })
    // 存储搜索的关键词
    saveHistory(key)
  }
  // 删除某个历史记录
  const delHistory = (key: string) => {
    setHistoryList(historyList.filter((item) => item !== key))
  }
  // 删除所有历史记录
  const clearAll = () => {
    setHistoryList([])
  }
  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={() => history(-1)}
        right={
          <span onClick={() => goSearch(keyWord)} className="search-text">
            搜索
          </span>
        }
      >
        {/* 搜索框 */}
        <SearchBar
          value={keyWord}
          onChange={onSearch}
          // 回车触发
          onSearch={goSearch}
          placeholder="请输入关键字搜索"
        />
      </NavBar>

      {/* 1. 搜索记录 */}
      {suggest.length === 0 && (
        <div
          className="history"
          style={{
            display: historyList.length === 0 ? 'none' : 'block',
          }}
        >
          <div className="history-header">
            <span>搜索历史</span>
            <span onClick={clearAll}>
              <Icon type="iconbtn_del" />
              清除全部
            </span>
          </div>

          <div className="history-list">
            {historyList.map((item) => (
              <span
                onClick={() => goSearch(item)}
                key={item}
                className="history-item"
              >
                <span className="text-overflow">{item}</span>
                <Icon
                  onClick={(e) => {
                    // 阻止冒泡
                    e.stopPropagation()
                    delHistory(item)
                  }}
                  type="iconbtn_essay_close"
                />
              </span>
            ))}
          </div>
        </div>
      )}
      {/* 2. 搜索联想词（交互体验） */}
      <div
        className={classnames('search-result', suggest.length ? 'show' : '')}
      >
        {suggest.map(
          (item) =>
            item && (
              <div
                onClick={() =>
                  goSearch(item.replace(`<span>${keyWord}</span>`, keyWord))
                }
                key={item}
                className="result-item"
              >
                <Icon className="icon-search" type="iconbtn_search" />
                {/* vue => v-html 解析html字符串 */}
                <div
                  className="result-value text-overflow"
                  dangerouslySetInnerHTML={{ __html: item }}
                ></div>
              </div>
            )
        )}
      </div>
    </div>
  )
}

export default SearchPage
